package org.fuckerfucker.urmomboot1.util;


import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Component
public class FileUtils {

    /**
     * 计算文件MD5哈希（基于文件内容）
     */
    public String calculateFileHash(MultipartFile file) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (InputStream is = file.getInputStream()) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = is.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        // 转换为16进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : md.digest()) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     * 将文件压缩为ZIP
     * @param sourceFile 源文件输入流
     * @param zipFilePath 压缩文件保存路径
     * @param entryName ZIP内部的文件名
     * @return 压缩后的文件大小（字节）
     */
    public long compressToZip(InputStream sourceFile, String zipFilePath, String entryName) throws IOException {
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath));
             BufferedInputStream bis = new BufferedInputStream(sourceFile)) {

            ZipEntry entry = new ZipEntry(entryName);
            zos.putNextEntry(entry);

            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesRead);
            }
            zos.closeEntry();
        }
        // 返回压缩后文件大小
        return new File(zipFilePath).length();
    }
}
